package com.fin.zw.aiqas.service;

import com.fin.zw.aiqas.entity.ConverseRule;
import com.fin.zw.aiqas.entity.QConverseRule;
import com.fin.zw.aiqas.entity.RuleInfo;
import com.fin.zw.aiqas.repository.ConverseRuleRepository;
import com.fin.zw.aiqas.util.BadRequestException;
import com.google.common.collect.Lists;
import com.querydsl.core.BooleanBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther:
 * @Description:
 * @Date: 2019/10/12 11:22
 */
@Service("converseRuleService")
public class ConverseRuleService {

    @Autowired
    private ConverseRuleRepository converseRuleRepository;

    /**
     * 查询1条
     *
     * @param id
     * @return
     */
    public ConverseRule findById(Long id) {
        ConverseRule converseRule = converseRuleRepository.findById(id).orElseThrow(() -> new BadRequestException("ConverseRule", "没有当前数据"));
        return converseRule;

    }

    /**
     * 保存
     *
     * @param converseRuleList
     */
    public void saveAll(List<ConverseRule> converseRuleList) {
        converseRuleRepository.saveAll(converseRuleList);
    }

    /**
     * 保存
     *
     * @param converseRule
     */
    public void saveAll(ConverseRule converseRule) {
        converseRuleRepository.save(converseRule);
    }


    /**
     * 去除RuleInfo
     *
     * @param converseId 文本ID
     * @param ruleInfoId 规则ID
     */
    public void removeRuleInfo(Long converseId, Long ruleInfoId) {
        QConverseRule qConverseRule = QConverseRule.converseRule;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qConverseRule.ruleInfo.id.eq(ruleInfoId));
        builder.and(qConverseRule.converseId.eq(converseId));
        Iterable<ConverseRule> converseRuleIterable = converseRuleRepository.findAll(builder);
        converseRuleRepository.deleteAll(converseRuleIterable);
    }

    /**
     * 根据 converseId 查询对应的 converseRule
     *
     * @param converseId
     * @return
     */
    public List<ConverseRule> queryByConverseId(Long converseId) {
        QConverseRule qConverseRule = QConverseRule.converseRule;
        Iterator<ConverseRule> converseRuleIterator = converseRuleRepository.findAll(qConverseRule.converseId.eq(converseId)).iterator();
        ArrayList<ConverseRule> converseRules = Lists.newArrayList(converseRuleIterator);
        return converseRules;
    }

    /**
     * 根据 ConverseRule 集合查询对应的所有的 ruleInfo
     *
     * @param converseId 文本ID
     * @return
     */
    public Set<RuleInfo> getRuleInfoByConverseId(Long converseId) {
        List<ConverseRule> converseRules = queryByConverseId(converseId);
        if (converseRules.isEmpty()) {
            return new HashSet<RuleInfo>();
        }
        Set<RuleInfo> ruleInfoSet = converseRules.stream().map(converseRule -> converseRule.getRuleInfo()).collect(Collectors.toSet());
        return ruleInfoSet;
    }



}
